let app = getApp()
const util = require('../../util/util.js')
import { deleteImgApi, deleteVideoApi } from "../../api/api.js"
Page({
  data: {
    level: ["/images/star.png",
      "/images/star.png",
      "/images/star.png",
      "/images/star.png",
      "/images/star.png",
    ],
    levelFont: "",
    hide: false,
    contentLength: 0,
    accounts: [],
    accountIndex: -1,
    files: [],
    imgUrl: [],
    address: "",
    loading: 1,
    videoSrc: "",
    video: "",
    cid: '',
    isDelelte: 0,
    isSupervising: false,
    isSupervsor: false,
    superviseSchoolId: 0
  },
  onLoad(options) {
    if (app.globalData.isSupervising == true) {
      this.setData({
        isSupervsor: true,
        isSupervising: app.globalData.isSupervising,
        address: app.globalData.superviseSchoolName,
        superviseSchoolId: app.globalData.superviseSchoolId
      })
    }
    if (app.globalData.isSuddenSupervising == true) {
      this.setData({
        isSupervsor: true,
        isSuddenSupervising: app.globalData.isSuddenSupervising,
        address: app.globalData.suddensuperviseSchoolName,
        superviseSchoolId: app.globalData.suddensuperviseSchoolId
      })
    }
    this.setData({
      imgUrl: []
    })
    dd.httpRequest({
      url: app.baseUrl + '/DingDingSystem/getAllValidInspectItems',
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      data: JSON.stringify({
        schoolId: app.globalData.departmentId
      }),
      dataType: 'json',
      success: res => {
        let accounts = [],
          categoryId = []
        for (let i = 0; i < res.data.length; i++) {
          accounts.push({
            item: res.data[i].category,
            realname: res.data[i].realname,
            checked: false
          })
          categoryId.push(res.data[i].categoryId)
        }
        this.setData({
          accounts: accounts,
          categoryId: categoryId
        })
        if (options.id != null) {
          this.setData({
            accountIndex: options.id - 1
          })
        }
      },
      fail: res => {
        dd.showToast({
          content: '网络异常！',
          type: 'fail'
        })
      },
      complete: () => {
        this.setData({
          loading: 0
        })
      }
    })
  },

  onUnload: function (e) {
    if (this.data.isDelelte == 0) {
      for (let i = 0; i < this.data.imgUrl.length; i++) {
        let target = this.data.imgUrl[i]
        deleteImgApi(target.split("image/")[1]).then((res) => {
          if (res.data == "success") {
            console.log("图片删除")
          }
        })
      }
      deleteVideoApi(this.data.video.split("video/")[1]).then((res) => {
        if(res.data == "success") {
          console.log("视频删除")
        }
      })
    }

  },





  showModal(e) {
    console.log("acountIndex:" + this.data.accountIndex)
    let accounts = this.data.accounts.map((item, index) => {
      return {
        item: item.item,
        checked: index == this.data.accountIndex ? true : false,
        realname: item.realname
      }
    })
    this.setData({
      modalName: "RadioModal",
      accounts: accounts,
      modalComfirm: this.data.selectedIndex != null ? true : false,
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  clickLevel(e) {
    let clickId = parseInt(e.currentTarget.id)
    console.log(clickId)
    let tempLevel = []
    let tempLevelFont
    for (let i = 1; i < 5; i++) {
      if (i <= clickId) {
        tempLevel.push("/images/star_fill.png")
      } else {
        tempLevel.push("/images/star.png")
      }
    }
    switch (clickId) {
      case 0:
        tempLevelFont = "一般"
        break
      case 1:
        tempLevelFont = "安全"
        break
      case 2:
        tempLevelFont = "一般"
        break
      case 3:
        tempLevelFont = "危险"
        break
      case 4:
        tempLevelFont = "非常危险"
        break
    }
    this.setData({
      level: tempLevel,
      levelFont: tempLevelFont
    })
  },
  //上传图片
  chooseImage() {
    var that = this;
    dd.chooseImage({
      count: 3,
      sourceType: ['camera', 'album'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        // dd.showLoading({
        //   content: "图片上传中",
        // })
        let tempImg = res.tempFilePaths
        for (let i = 0; i < res.tempFilePaths.length; i++) {
          dd.uploadFile({
            url: app.baseUrl + '/DingDingSystem/fileUpload',
            filePath: res.tempFilePaths[i],
            fileName: 'file',
            fileType: 'image',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success: res => {
              if (res.statusCode == 500) {
                dd.showToast({
                  content: "图片上传失败",
                  type: 'fail',
                  duration: 2000,
                  // image: "/image/error.png"
                })
              } else {
                dd.showToast({
                  content: "上传成功",
                  type: "success",
                  duration: 2000,
                })
                //返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                that.setData({
                  files: that.data.files.concat(tempImg[i])
                })
                if (that.data.files.length == 3) {
                  that.setData({
                    hide: true
                  })
                }
                this.data.imgUrl.push(res.data)
              }
            },
            fail: res => {
              console.log("失败-----" + res)
              dd.showToast({
                content: "图片上传失败",
                type: 'fail',
                duration: 2000,
                // image: "/image/error.png"
              })
            }
          })
        }
      }
    })
  },
  //显示图片
  previewImage(e) {
    dd.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  //删除照片
  deleteImage(e) {
    console.log("e", e)
    let targetIndex = e.currentTarget.dataset.index
    let target = this.data.imgUrl[targetIndex]
    console.log(target.split("image/")[1])
    let temp = []
    let tempUrl = []
    let filesLength = this.data.files.length
    for (let i = 0; i < filesLength; i++) {
      if (i != targetIndex) {
        temp.push(this.data.files[i])
        tempUrl.push(this.data.imgUrl[i])
      }
    }
    console.log(temp)
    dd.showActionSheet({
      items: ['删除这张照片'],
      cancelButtonText: '取消',
      success: (res) => {
        if (res.index != -1) {
          this.setData({
            files: temp,
            imgUrl: tempUrl
          })
          deleteImgApi(target.split("image/")[1]).then((res) => {
            if (res.data == "success") {
              if (filesLength == 3) {
                this.setData({
                  hide: false
                })
              }
            }
          })
        }
      }
    })
  },
  radioSelect(e) {
    let radioIndex = e.currentTarget.dataset.index,
      accounts = this.data.accounts.map((item, index) => {
        return {
          item: item.item,
          checked: index == radioIndex ? true : false,
          realname: item.realname
        }
      }),
      status
    this.setData({
      accounts: accounts,
      selectedIndex: radioIndex
    })
    if (this.data.selectedIndex != null) status = true
    else status = false
    this.setData({
      modalComfirm: status
    })
  },
  confirmSelect(e) {
    this.setData({
      accountIndex: this.data.selectedIndex,
      modalName: null
    })
  },

  //提交表单
  formSubmit(e) {
    let schoolId
    let inspectConditionId
    let superviseId
    let suddenSuperviseId
    if (app.globalData.isSupervising == true) {
      schoolId = app.globalData.superviseSchoolId
      inspectConditionId = -1
      superviseId = -app.globalData.superviseId
    } else if (app.globalData.isSuddenSupervising == true) {
      schoolId = app.globalData.suddensuperviseSchoolId
      inspectConditionId = -1
      suddenSuperviseId = app.globalData.suddensuperviseId
    } else {
      schoolId = app.globalData.departmentId
      inspectConditionId = 0
    }
    this.setData({
      isDelelte: 1
    })
    
    let waringInfo = ""
    if (this.data.accountIndex == -1) {
      waringInfo = "请选择隐患类型"
    } else if (e.detail.value.address == "") {
      waringInfo = "请输入隐患地点"
    } else if (this.data.levelFont == "") {
      waringInfo = "请选择隐患等级"
    } else if (this.data.recordContent == "" || !this.data.recordContent) {
      waringInfo = "请输入详细问题"
    } 
    else if(this.data.imgUrl.length == 0 && this.data.video == "") {
      waringInfo = "请附上照片或视频"
    } 
    else {
      let level = 0
      switch (this.data.levelFont) {
        case "安全":
          level = 1
          break
        case "一般":
          level = 2
          break
        case "危险":
          level = 3
          break
        case "非常危险":
          level = 4
          break
      }
      let photo = ""
      for (let j = 0; j < this.data.imgUrl.length; j++) {
        photo += this.data.imgUrl[j]
        if (j != this.data.imgUrl.length - 1) {
          photo += ","
        }
      }
      dd.httpRequest({
        url: app.baseUrl + '/DingDingSystem/safetyReport',
        method: 'POST',
        headers: {
          "Content-Type": "application/json"
        },
        data: JSON.stringify({
          schoolId: schoolId,
          safetyLevel: level,
          categoryId: this.data.categoryId[this.data.accountIndex],
          address: e.detail.value.address,
          content: this.data.recordContent,
          photo: photo,
          reporter: app.globalData.userId,
          video: this.data.video,
          inspectConditionId: inspectConditionId,
          superviseId: superviseId,
          suddenSuperviseId: suddenSuperviseId
        }),
        dataType: 'json',
        success: res => {
          if (res.data.res == "success") {
            let safetySceneId = res.data.data
            // 推送
            console.log('==========12241', safetySceneId);
            dd.httpRequest({
              url: app.baseUrl + '/DingDingSystem/getAccessTokenForSendMsg',
              method: 'GET',
              data: {
                schoolId: app.globalData.departmentId
              },
              dataType: 'json',
              success: res => {
                console.log('============tt3222', res);
                let access_token = res.data.access_token
                
                dd.httpRequest({
                  url: app.baseUrl + '/DingDingSystem/getChargeManDingDingId',
                  method: 'POST',
                  headers: {
                    "Content-Type": "application/json"
                  },
                  data: JSON.stringify({
                    // safetySceneId:safetySceneId, 隐患提交后，通过这个接口插入查找出来的推送人 userPush
                    categoryId: this.data.categoryId[this.data.accountIndex],
                    schoolId: this.data.isSupervsor == true ? this.data.superviseSchoolId : app.globalData.departmentId
                  }),
                  dataType: 'json',
                  success: res => {
                    console.log("res", res);
                    let unbind = []
                    for (let i = 0; i < res.data.length; i++) {
                      if (res.data[i].res == "success") {
                        let datetime = util.formatTime(new Date())
                        console.log(res.data[i].msg);
                        dd.httpRequest({
                          url: app.baseUrl + '/DingDingSystem/sendMessage',
                          headers: {
                            "Content-Type": "application/json"
                          },
                          data: JSON.stringify({
                            schoolId: app.globalData.departmentId,
                            template: 1,
                            accessToken: access_token,
                            touser: res.data[i].msg,
                            safetySceneId: safetySceneId,
                            data: {
                              first: {
                                value: "【安全现场隐患】"
                              },
                              keyword1: {
                                value: app.globalData.realname
                              },
                              keyword2: {
                                value: datetime
                              },
                              keyword3: {
                                value: `在${e.detail.value.address}发现${this.data.accounts[this.data.accountIndex].item}类型隐患，请及时查看！`
                              }
                            }
                          }),
                          method: 'POST',
                          dataType: 'json'
                        })
                        dd.reLaunch({
                          url: '/page/safetysence/safetysence'
                        })
                      } else {
                        //获取所有未绑定主管姓名
                        unbind.push(res.data[i].msg)
                      }
                    }
                    //提示未绑定信息
                    if (unbind.length != 0) {
                      let msg = unbind.join("、") + "主管未绑定服务号，无法正常接收推送！"
                      dd.confirm({
                        title: "温馨提示",
                        content: msg,
                      })
                    }
                  }
                })
              }
            })

          } else {
            dd.showToast({
              content: '上报失败',
              type: "fail"
            })
          }
        },
        fail: () => {
          dd.showToast({
            content: '网络异常！',
            type: "fail"
          })
        }
      })
    }
    if (waringInfo != "") {
      dd.showToast({
        content: waringInfo,
        type: "fail"
      })
    }
  },
  getAddress(e) {
    this.setData({
      address: e.detail.value
    })
  },
  inputContent(e) {
    e.detail.value = app.trim(e.detail.value)
    this.setData({
      recordContent: e.detail.value,
      contentLength: parseInt(e.detail.value.length)
    })
  },
  //新增视频录制功能
  press: function (e) {
    dd.chooseVideo({
      sourceType: ['camera'],
      maxDuration: 10,
      success: res => {
        if (res.size > 2097152) {
          dd.showToast({
            content: '文件大于2M！',
            type: 'fail'
          })
        } else {
          dd.showLoading({
            content: '视频上传中...',
          })
          dd.uploadFile({
            url: app.baseUrl + '/DingDingSystem/fileUpload2',
            filePath: res.tempFilePath,
            fileName: 'file',
            fileType: 'video',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success: res => {
              console.log(res.data)
              this.setData({
                videoSrc: app.imageUrl + res.data,
                video: res.data
              })
              dd.hideLoading()
            }
          })
        }
      },
      fail(res) {
        console.log("-------调用失败")
      }
    })
  },
  delelteVideo: function (e) {
    let target = this.data.video
    dd.showActionSheet({
      items: ['删除视频'],
      success: res => {
        if (res.index != -1) {
          deleteVideoApi(target.split("video/")[1]).then((res) => {
            if (res.data == "success") {
              this.setData({
                video: "",
                videoSrc: ""
              })
            }
          })
        }
      }
    })
  },


});